<template>
	<view class="">
		<!-- 加载状态 999999111111111 -->
		<view v-if="loading" class="loading-container">
			<van-loading type="spinner" color="#3c91ff" size="large" />
			<text style="margin-top: 10rpx; color: #3c91ff;">加载中...</text>
		</view>

		<!-- 空状态555555 -->
		<view class="" style="width: 116rpx; height: 182rpx; margin: 0 auto; padding: 300rpx 0;"
			v-if="!infos.length && !loading">
			<image src="/static/image/item.png" mode=""></image>
			<text style="margin-top: 20rpx; color: #999; font-size: 28rpx;">暂无地址数据</text>
		</view>

		<!-- 地址列表 -->
		<scroll-view scroll-y="true" style="height: 80vh;" v-else-if="!loading">
			<view class="ft_box">
				<view class="add_list" v-for="(item, index) in infos" :key="item.id" @click="selectAddress(item)">
					<view class="add_ft">
						{{ item.building }} {{ item.detailAddress }}
					</view>
					<view class="item_line">
						<text>{{ item.name }}</text>
						<text class="" style="margin-left: 30rpx;">{{ item.phone }}</text>
					</view>
					<view class=""
						style="display: flex; justify-content: space-between; align-items: center; margin-top: 10rpx;">
						<view style="display: flex; color: #3c91ff;" :class="item.isDefault === 1 ? '':'yc'">
							<view class="" style="width: 22rpx; height: 22rpx;">
								<van-icon name="checked" />
							</view>
							<view class="" style="font-size: 28rpx; margin-left: 20rpx;">默认地址</view>
						</view>
						<view class="" style="display: flex;">
							<view class="btn_ck" style="margin-right: 10rpx; color: #3c91ff;"
								@click.native.stop="edititem(item)">
								<van-icon name="records-o" />编辑
							</view>
							<view class="btn_ck" style="color: #f14d4e; margin-left: 20rpx;"
								@click.native.stop="deleteitem(item)">
								<van-icon name="delete-o" />删除
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 新增地址按钮 -->
		<view style="padding-bottom: 80rpx; position: absolute; bottom: 50rpx; width: 100%; text-align: center;">
			<button
				style="background-color: #3c91ff; color: white; border-radius: 50rpx; width: 90%; height: 100rpx; line-height: 100rpx; font-size: 36rpx;"
				@click="sub" :disabled="loading">
				{{ loading ? '加载中...' : (addressType === 'pickup' ? '新增取货地址' : '新增收货地址') }}
			</button>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		ref,
		onMounted,
		watch
	} from 'vue';
	import {
		getCampusAddress,
		deleteCampusAddress
	} from '@/package/api/selList.js';
	import {
		updateCampusAddress
	} from '@/package/api/update.js';

	// 状态管理
	const loading = ref(false);
	const infos = ref([]);
	// 明确地址类型：pickup(取货)/receive(收货)
	const addressType = ref('');
	// 页面标题
	const pageTitle = ref('地址管理');

	// 工具函数
	const showToast = (title, icon = 'none') => {
		uni.showToast({
			title,
			icon,
			duration: 2000
		});
	};

	const showLoading = (title = '加载中...') => {
		loading.value = true;
		uni.showLoading({
			title,
			mask: true
		});
	};

	const hideLoading = () => {
		loading.value = false;
		uni.hideLoading();
	};

	// 设置默认地址
	const setDefaultAddress = async (addressId) => {
		// 查找当前默认地址
		const currentDefault = infos.value.find(addr => addr.isDefault === 1);

		// 如果当前点击的已经是默认地址，则无需操作
		if (currentDefault && currentDefault.id === addressId) {
			return;
		}

		showLoading('设置中...');

		try {
			// 构建要更新的数据
			const updateData = {
				id: addressId,
				isDefault: 1
			};

			// 如果存在当前默认地址，将其设为非默认
			if (currentDefault) {
				await updateCampusAddress({
					id: currentDefault.id,
					isDefault: 0
				});
			}

			// 设置新的默认地址
			const res = await updateCampusAddress(updateData);

			if (res.code === 200) {
				// 更新本地数据
				infos.value = infos.value.map(addr => {
					if (addr.id === addressId) {
						return {
							...addr,
							isDefault: 1
						};
					} else if (addr.isDefault === 1) {
						return {
							...addr,
							isDefault: 0
						};
					}
					return addr;
				});

				showToast('默认地址设置成功', 'success');
			} else {
				showToast(res.message || '设置失败', 'none');
			}
		} catch (error) {
			console.error('设置默认地址失败', error);
			showToast('网络错误，请稍后再试', 'none');
		} finally {
			hideLoading();
		}
	};

	// 生命周期钩子
	onShow(() => {
		loadAddressList();
	});

	onUnload(() => {
		// 清理操作
	});

	// 业务逻辑
	const loadAddressList = async () => {
		showLoading();
		try {
			// 真实API调用获取地址列表
			// 可以根据addressType参数过滤地址列表，这里假设后端API支持此参数
			// 若后端不支持，可以在前端过滤
			const res = await getCampusAddress();
			if (res.code === 200) {
				infos.value = res.data || [];
			} else {
				showToast(res.message || '获取地址失败', 'none');
			}
		} catch (error) {
			console.error('获取地址失败', error);
			showToast('网络错误，请稍后再试', 'none');
		} finally {
			hideLoading();
		}
	};

	// 新增地址
	const sub = () => {
		if (loading.value) return;
		uni.navigateTo({
			url: `/package/pages/address_rep/address_rep?addressType=${addressType.value}`
		});
	};

	// 编辑地址
	const edititem = (item) => {
		if (loading.value) return;
		uni.navigateTo({
			url: `/package/pages/address_rep/address_rep?edit=${JSON.stringify(item)}&addressType=${addressType.value}`
		});
	};

	// 删除地址
	const deleteitem = async (item) => {
		if (loading.value) return;

		uni.showModal({
			title: '提示',
			content: '确定要删除此地址吗？',
			success: async (res) => {
				if (res.confirm) {
					showLoading('删除中...');
					try {
						// 调用删除API
						const delRes = await deleteCampusAddress(item.id);
						if (delRes.code === 200) {
							// 从列表中移除
							infos.value = infos.value.filter(addr => addr.id !== item.id);
							showToast('删除成功', 'success');
						} else {
							showToast(delRes.message || '删除失败', 'none');
						}
					} catch (error) {
						console.error('删除地址失败', error);
						showToast('网络错误，请稍后再试', 'none');
					} finally {
						hideLoading();
					}
				}
			}
		});
	};

	// 选择地址
	const selectAddress = (item) => {
		if (loading.value) return;
		console.log('选择的地址项:', item, '类型:', addressType.value);

		// 根据地址类型触发不同事件
		if (addressType.value === 'pickup') {
			// 触发取货地址选择事件
			uni.$emit('selectPickAddress', item);
		} else if (addressType.value === 'receive') {
			// 触发收货地址选择事件
			uni.$emit('selectReceiveAddress', item);
		} else {
			// 默认事件
			uni.$emit('selectAddress', item);
		}

		// 返回上一页
		uni.navigateBack({
			delta: 1
		});
	};

	// 页面加载时初始化
	onLoad((options) => {
		// 接收地址类型参数
		addressType.value = options.addressType || (options.isPickAddress ? 'pickup' : '');

		// 设置页面标题
		if (addressType.value === 'pickup') {
			pageTitle.value = '取货地址管理';
			uni.setNavigationBarTitle({
				title: '取货地址管理'
			});
		} else if (addressType.value === 'receive') {
			pageTitle.value = '收货地址管理';
			uni.setNavigationBarTitle({
				title: '收货地址管理'
			});
		}
	});

	// 监听地址类型变化
	watch(addressType, (newVal) => {
		console.log('地址类型变更为:', newVal);
	});
</script>

<style scoped>
	/* 样式保持不变 */
	.add_list {
		margin: 30rpx;
		padding: 30rpx;
		border-radius: 20rpx;
		box-shadow: 0 0 10rpx 0 #f3f3f3, 0 0 20rpx 0 #f6f6f6;
		border: 1rpx solid #e8f2ff;
		height: 240rpx;
		gap: 27rpx;
		display: flex;
		flex-direction: column;
	}

	.btn_ck {
		background-color: #f5f5f5;
		border-radius: 10rpx;
		width: 120rpx;
		height: 60rpx;
		border: 1rpx solid #dddddd;
		line-height: 60rpx;
		font-size: 28rpx;
		text-align: center;
	}

	.yc {
		opacity: 0;
	}

	.add_ft {
		font-size: 34rpx;
		font-weight: bold;
	}

	.item_line {
		color: #999;
		font-size: 30rpx;
	}

	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 100vh;
	}
</style>